use serde::{Deserialize, Serialize};
use std::path::Path;
use std::env;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ClientConfig {
    pub connection: ConnectionSettings,
    pub transfer: TransferSettings,
    pub ui: UiSettings,
    pub security: SecuritySettings,
    pub performance: PerformanceSettings,
    pub logging: LoggingSettings,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConnectionSettings {
    pub default_host: String,
    pub default_port: u16,
    pub connection_timeout: u64,
    pub data_timeout: u64,
    pub retry_attempts: u32,
    pub retry_delay: u64,
    pub keep_alive: bool,
    pub keep_alive_interval: u64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TransferSettings {
    pub default_mode: String, // "passive" or "active"
    pub default_type: String, // "binary" or "ascii"
    pub chunk_size: usize,
    pub buffer_size: usize,
    pub enable_resume: bool,
    pub enable_checksum: bool,
    pub checksum_algorithms: Vec<String>,
    pub max_concurrent_transfers: usize,
    pub transfer_timeout: u64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UiSettings {
    pub show_colors: bool,
    pub show_progress: bool,
    pub progress_width: usize,
    pub show_speed: bool,
    pub show_eta: bool,
    pub verbose_output: bool,
    pub interactive_mode: bool,
    pub command_history_size: usize,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SecuritySettings {
    pub verify_ssl: bool,
    pub ssl_cert_path: String,
    pub enable_encryption: bool,
    pub encryption_algorithm: String,
    pub save_passwords: bool,
    pub password_file: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PerformanceSettings {
    pub enable_caching: bool,
    pub cache_size: usize,
    pub cache_ttl: u64,
    pub enable_compression: bool,
    pub compression_level: u8,
    pub enable_prefetch: bool,
    pub prefetch_size: usize,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LoggingSettings {
    pub level: String,
    pub file: String,
    pub max_file_size: u64,
    pub max_files: u32,
    pub format: String,
    pub enable_console: bool,
}

impl ClientConfig {
    /// 从文件加载配置
    pub fn load<P: AsRef<Path>>(path: P) -> anyhow::Result<Self> {
        let content = std::fs::read_to_string(path)?;
        let mut config: ClientConfig = toml::from_str(&content)?;
        
        // 应用环境变量覆盖
        config.apply_env_overrides()?;
        
        config.validate()?;
        Ok(config)
    }
    
    /// 从环境变量加载配置
    pub fn load_from_env() -> anyhow::Result<Self> {
        let mut config = Self::default();
        config.apply_env_overrides()?;
        config.validate()?;
        Ok(config)
    }
    
    /// 应用环境变量覆盖
    fn apply_env_overrides(&mut self) -> anyhow::Result<()> {
        // 连接设置
        if let Ok(host) = env::var("FTP_CLIENT_HOST") {
            self.connection.default_host = host;
        }
        if let Ok(port) = env::var("FTP_CLIENT_PORT") {
            self.connection.default_port = port.parse()?;
        }
        if let Ok(timeout) = env::var("FTP_CLIENT_TIMEOUT") {
            self.connection.connection_timeout = timeout.parse()?;
        }
        if let Ok(retry) = env::var("FTP_CLIENT_RETRY_ATTEMPTS") {
            self.connection.retry_attempts = retry.parse()?;
        }
        if let Ok(keep_alive) = env::var("FTP_CLIENT_KEEP_ALIVE") {
            self.connection.keep_alive = keep_alive.parse()?;
        }
        
        // 传输设置
        if let Ok(mode) = env::var("FTP_CLIENT_MODE") {
            self.transfer.default_mode = mode;
        }
        if let Ok(transfer_type) = env::var("FTP_CLIENT_TYPE") {
            self.transfer.default_type = transfer_type;
        }
        if let Ok(chunk_size) = env::var("FTP_CLIENT_CHUNK_SIZE") {
            self.transfer.chunk_size = chunk_size.parse()?;
        }
        if let Ok(max_concurrent) = env::var("FTP_CLIENT_MAX_CONCURRENT") {
            self.transfer.max_concurrent_transfers = max_concurrent.parse()?;
        }
        if let Ok(enable_resume) = env::var("FTP_CLIENT_ENABLE_RESUME") {
            self.transfer.enable_resume = enable_resume.parse()?;
        }
        if let Ok(enable_checksum) = env::var("FTP_CLIENT_ENABLE_CHECKSUM") {
            self.transfer.enable_checksum = enable_checksum.parse()?;
        }
        
        // UI设置
        if let Ok(show_colors) = env::var("FTP_CLIENT_SHOW_COLORS") {
            self.ui.show_colors = show_colors.parse()?;
        }
        if let Ok(show_progress) = env::var("FTP_CLIENT_SHOW_PROGRESS") {
            self.ui.show_progress = show_progress.parse()?;
        }
        if let Ok(verbose) = env::var("FTP_CLIENT_VERBOSE") {
            self.ui.verbose_output = verbose.parse()?;
        }
        if let Ok(interactive) = env::var("FTP_CLIENT_INTERACTIVE") {
            self.ui.interactive_mode = interactive.parse()?;
        }
        
        // 安全设置
        if let Ok(verify_ssl) = env::var("FTP_CLIENT_VERIFY_SSL") {
            self.security.verify_ssl = verify_ssl.parse()?;
        }
        if let Ok(enable_encryption) = env::var("FTP_CLIENT_ENABLE_ENCRYPTION") {
            self.security.enable_encryption = enable_encryption.parse()?;
        }
        if let Ok(save_passwords) = env::var("FTP_CLIENT_SAVE_PASSWORDS") {
            self.security.save_passwords = save_passwords.parse()?;
        }
        
        // 性能设置
        if let Ok(enable_cache) = env::var("FTP_CLIENT_ENABLE_CACHE") {
            self.performance.enable_caching = enable_cache.parse()?;
        }
        if let Ok(cache_size) = env::var("FTP_CLIENT_CACHE_SIZE") {
            self.performance.cache_size = cache_size.parse()?;
        }
        if let Ok(enable_compression) = env::var("FTP_CLIENT_ENABLE_COMPRESSION") {
            self.performance.enable_compression = enable_compression.parse()?;
        }
        
        // 日志设置
        if let Ok(log_level) = env::var("FTP_CLIENT_LOG_LEVEL") {
            self.logging.level = log_level;
        }
        if let Ok(log_file) = env::var("FTP_CLIENT_LOG_FILE") {
            self.logging.file = log_file;
        }
        if let Ok(log_format) = env::var("FTP_CLIENT_LOG_FORMAT") {
            self.logging.format = log_format;
        }
        if let Ok(enable_console) = env::var("FTP_CLIENT_LOG_CONSOLE") {
            self.logging.enable_console = enable_console.parse()?;
        }
        
        Ok(())
    }
    
    /// 保存配置到文件
    pub fn save<P: AsRef<Path>>(&self, path: P) -> anyhow::Result<()> {
        let content = toml::to_string_pretty(self)?;
        std::fs::write(path, content)?;
        Ok(())
    }
    
    /// 验证配置
    pub fn validate(&self) -> anyhow::Result<()> {
        if self.connection.default_port == 0 {
            return Err(anyhow::anyhow!("Invalid port number"));
        }
        
        if self.transfer.chunk_size == 0 {
            return Err(anyhow::anyhow!("Invalid chunk size"));
        }
        
        if self.transfer.max_concurrent_transfers == 0 {
            return Err(anyhow::anyhow!("Invalid max concurrent transfers"));
        }
        
        if !matches!(self.transfer.default_mode.as_str(), "passive" | "active") {
            return Err(anyhow::anyhow!("Invalid transfer mode"));
        }
        
        if !matches!(self.transfer.default_type.as_str(), "binary" | "ascii") {
            return Err(anyhow::anyhow!("Invalid transfer type"));
        }
        
        if self.security.enable_encryption && self.security.encryption_algorithm.is_empty() {
            return Err(anyhow::anyhow!("Encryption algorithm must be specified when encryption is enabled"));
        }
        
        Ok(())
    }
    
    /// 获取默认配置
    pub fn default() -> Self {
        Self {
            connection: ConnectionSettings {
                default_host: "localhost".to_string(),
                default_port: 21,
                connection_timeout: 30,
                data_timeout: 300,
                retry_attempts: 3,
                retry_delay: 5,
                keep_alive: true,
                keep_alive_interval: 30,
            },
            transfer: TransferSettings {
                default_mode: "passive".to_string(),
                default_type: "binary".to_string(),
                chunk_size: 8192,
                buffer_size: 65536,
                enable_resume: true,
                enable_checksum: true,
                checksum_algorithms: vec!["md5".to_string(), "sha256".to_string()],
                max_concurrent_transfers: 5,
                transfer_timeout: 0, // 0 = unlimited
            },
            ui: UiSettings {
                show_colors: true,
                show_progress: true,
                progress_width: 50,
                show_speed: true,
                show_eta: true,
                verbose_output: false,
                interactive_mode: false,
                command_history_size: 100,
            },
            security: SecuritySettings {
                verify_ssl: true,
                ssl_cert_path: String::new(),
                enable_encryption: false,
                encryption_algorithm: "aes256".to_string(),
                save_passwords: false,
                password_file: "data/passwords.json".to_string(),
            },
            performance: PerformanceSettings {
                enable_caching: true,
                cache_size: 1048576, // 1MB
                cache_ttl: 3600, // 1 hour
                enable_compression: false,
                compression_level: 6,
                enable_prefetch: true,
                prefetch_size: 32768, // 32KB
            },
            logging: LoggingSettings {
                level: "info".to_string(),
                file: "logs/ftp_client.log".to_string(),
                max_file_size: 10485760, // 10MB
                max_files: 5,
                format: "json".to_string(),
                enable_console: true,
            },
        }
    }
    
    /// 获取配置摘要
    pub fn summary(&self) -> String {
        format!(
            "FTP Client Configuration:\n\
            - Default Host: {}\n\
            - Default Port: {}\n\
            - Transfer Mode: {}\n\
            - Transfer Type: {}\n\
            - Max Concurrent: {}\n\
            - Enable Resume: {}\n\
            - Enable Checksum: {}\n\
            - Show Colors: {}\n\
            - Show Progress: {}\n\
            - Verbose Output: {}",
            self.connection.default_host,
            self.connection.default_port,
            self.transfer.default_mode,
            self.transfer.default_type,
            self.transfer.max_concurrent_transfers,
            self.transfer.enable_resume,
            self.transfer.enable_checksum,
            self.ui.show_colors,
            self.ui.show_progress,
            self.ui.verbose_output
        )
    }
}
